import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mobkit_dashed_border/mobkit_dashed_border.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/comment/comment_views.dart';
import 'package:xvideos/hj_page/find/acg_game_detail_logic.dart';
import 'package:xvideos/hj_page/find/acg_game_recommend_page.dart';
import 'package:xvideos/hj_utils/sliver_delegate.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/banner/ads_banner_widget.dart';
import 'package:xvideos/tools_base/indicator/custom_tab_indicator.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/widget/keep_alive_widget.dart';

//acg游戏详情
class AcgGameDetailPage extends StatefulWidget {
  final String id;

  const AcgGameDetailPage({super.key, this.id = ''});

  @override
  State<AcgGameDetailPage> createState() => _AcgGameDetailPageState();
}

class _AcgGameDetailPageState extends State<AcgGameDetailPage> {
  late AcgGameDetailLogic logic;
  late String tag;

  @override
  void initState() {
    super.initState();
    tag = widget.id + DateTime.now().millisecondsSinceEpoch.toString();
    logic = AcgGameDetailLogic(gameId: widget.id);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AcgGameDetailLogic>(
      init: logic,
      tag: tag,
      builder: (_) {
        return Scaffold(
          appBar: AppBar(title: Text(_.detailInfo?.title ?? '')),
          body: Padding(
              padding: EdgeInsets.symmetric(horizontal: 0),
              child: () {
                if (_.detailInfo == null) return LoadingCenterWidget();
                if (_.detailInfo?.id == null) return CErrorWidget();
                return _buildSoureContent();
              }()),
        );
      },
    );
  }

  _buildSoureContent() {
    return ExtendedNestedScrollView(
      onlyOneScrollInBody: true,
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [
          //图片
          if (logic.detailInfo?.seriesCover?.isNotEmpty == true)
            SliverToBoxAdapter(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: ImageCollectionWidget(
                  imgs: logic.detailInfo?.seriesCover,
                  showCIndicator: true,
                  showIndex: false,
                  aspectRatio: 343 / 143,
                ),
              ),
            ),
          _buildContent(),
          SliverPersistentHeader(
            pinned: true,
            delegate: MySliverDelegate(
              maxHeight: 44,
              minHeight: 44,
              child: Container(
                child: _buildSection(),
                color: AppColors.primaryColor,
              ),
            ),
          ),
        ];
      },
      body: TabBarView(
        controller: logic.tabCtr,
        children: [
          AcgGameRecommendPage(mediaModel: logic.detailInfo).keepAlive,
          CommentView(
            logic.gameId,
            objType: "video",
            totalCallback: (value) {
              logic.totalCtCount.value = value;
            },
          ).keepAlive,
        ],
      ),
    );
  }

  //推荐和评论
  _buildSection() {
    return TabBar(
      padding: EdgeInsets.only(bottom: 6),
      tabAlignment: TabAlignment.start,
      controller: logic.tabCtr,
      isScrollable: true,
      labelColor: Colors.white,
      labelStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
      unselectedLabelColor: Color(0xffE0E0E0),
      unselectedLabelStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
      indicator: CustomIndicator(
        width: 16,
        height: 4,
        topLeft: 3,
        topRight: 3,
        bottomLeft: 0,
        bottomRight: 0,
        color: AppColors.actionRed,
      ),
      tabs: List.generate(
        logic.tabs.length,
        (index) => Container(
          padding: EdgeInsets.symmetric(vertical: 6),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(logic.tabs[index]),
              if (index == 1) ...[
                Obx(
                  () => Container(
                    padding: EdgeInsets.only(left: 2),
                    child: Text(
                      '${logic.totalCtCount.value == 0 ? '' : logic.totalCtCount.value}',
                      style: textStyle(12, AppColors.actionRed, FontWeight.w500),
                    ),
                  ),
                ),
              ]
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildContent() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            10.sizeBoxH,
            Text(
              '游戏简介:',
              style: TextStyle(
                fontSize: 16,
                color: Color(0xffDCDCDC),
                fontWeight: FontWeight.w500,
              ),
            ),
            18.sizeBoxH,
            Text(
              '${logic.detailInfo?.content ?? ''}',
              style: TextStyle(
                fontSize: 14,
                color: Color(0xffDCDCDC),
                fontWeight: FontWeight.w400,
              ),
            ),
            18.sizeBoxH,
            _buildRightWidget(),
            if (logic.detailInfo?.tags != null && logic.detailInfo?.tags?.isNotEmpty == true) ...[
              20.sizeBoxH,
              Wrap(
                spacing: 10,
                runSpacing: 0,
                children: List.generate(logic.detailInfo?.tags?.length ?? 0, (index) {
                  final tag = logic.detailInfo?.tags?[index];
                  return Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(.05),
                      borderRadius: BorderRadius.circular(3),
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    child: Text(
                      '#${tag?.name ?? ''}',
                      style: TextStyle(
                        fontSize: 12,
                        color: Color(0xff989898),
                      ),
                    ),
                  );
                }),
              ),
            ],
            20.sizeBoxH,
            _buildInfoStatus(),
            18.sizeBoxH,
            0.5.line,
            18.sizeBoxH,
          ],
        ),
      ),
    );
  }

  _buildRightWidget() {
    return GetBuilder<AcgGameDetailLogic>(
      tag: tag,
      id: 'link',
      builder: (_) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (_.detailInfo?.gameLockType == 0) ...[
            //无需解锁
            Row(
              children: [
                Spacer(),
                InkWell(
                  onTap: () => logic.onLinkClickAction(),
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                    decoration: BoxDecoration(
                      border: DashedBorder.fromBorderSide(
                        dashLength: 3,
                        side: BorderSide(
                          color: Colors.white.withOpacity(.4),
                          width: 1,
                        ),
                      ),
                      borderRadius: BorderRadius.circular(32),
                    ),
                    child: EasyRichText(
                      '点击复制「种子资源」',
                      defaultStyle: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w400),
                      patternList: [
                        EasyRichTextPattern(
                          targetString: '「种子资源」',
                          style: TextStyle(color: Color(0xffE1351F)),
                        ),
                      ],
                    ),
                  ),
                ),
                Spacer(),
              ],
            )
          ] else ...[
            //金币解锁
            InkWell(
              onTap: () => logic.showAlert(),
              child: Container(
                height: 124,
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  border: DashedBorder.fromBorderSide(
                    dashLength: 3,
                    side: BorderSide(
                      color: Color(0xffC781FF),
                      width: 1,
                    ),
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Colors.white.withOpacity(.1),
                  ),
                  child: Text(
                    '内容已隐藏，解锁后查看',
                    style: textStyle(14, Colors.white, FontWeight.w400),
                  ),
                ),
              ),
            ),
            18.sizeBoxH,
            InkWell(
              onTap: () => logic.showAlert(),
              child: Container(
                height: 44,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  color: AppColors.actionRed,
                ),
                child: Text(
                  '${_.detailInfo?.newsType == "SEED_LINK" ? _.detailInfo?.originCoins ?? 0 : _.detailInfo?.coins ?? 0}金币/立即解锁',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            )
          ]
        ],
      ),
    );
  }

  //观看/点赞/解锁
  _buildInfoStatus() {
    return Row(
      children: [
        //观看
        _buildStatusItem('count_eye.png'.communityPath, logic.detailInfo?.playCount.humanizeFormat ?? '', false),
        30.sizeBoxW,
        //收藏
        GetBuilder<AcgGameDetailLogic>(
          tag: tag,
          id: 'collect',
          builder: (controller) => InkWell(
            onTap: logic.onCollectionAction,
            child: _buildStatusItem(
              logic.detailInfo?.hasCollected == true ? 'collect_red.png'.communityPath : 'collect_empty.png'.communityPath,
              logic.detailInfo?.collectCount?.humanizeFormatDefault("0") ?? '',
              logic.detailInfo?.hasCollected == true,
            ),
          ),
        ),
        30.sizeBoxW,
        //喜欢
        GetBuilder<AcgGameDetailLogic>(
          tag: tag,
          id: 'like',
          builder: (controller) => InkWell(
            onTap: logic.onLikeAction,
            child: _buildStatusItem(
              logic.detailInfo?.hasLiked == true ? 'like_red.png'.communityPath : 'like_empty.png'.communityPath,
              logic.detailInfo?.likeCount?.humanizeFormatDefault("0") ?? '',
              logic.detailInfo?.hasLiked == true,
            ),
          ),
        ),
        30.sizeBoxW,
        _buildStatusItem(
          'locked_white.png'.communityPath,
          logic.detailInfo?.purchaseCount.humanizeFormat ?? '',
          false,
        ),
      ],
    );
  }

  _buildStatusItem(String imgPath, String count, bool select) {
    return Row(
      children: [
        Image.asset(
          imgPath,
          width: 20,
          color: select ? null : Color(0xff989898),
        ),
        2.sizeBoxW,
        Text(
          count,
          style: TextStyle(
            fontSize: 12,
            color: select ? AppColors.actionRed : Color(0xff989898),
          ),
        ),
      ],
    );
  }
}
